#include "../common/net.hpp"
#include "../common/message.hpp"
#include "../client/rpc_caller.hpp"
#include "../client/rpc_requestor.hpp"
#include <muduo/base/Logging.h>

void onMessage(const RPC::BaseConnection::Ptr& conn, RPC::BaseMessage::Ptr& msg)
{
    std::string body = msg->serialize();
    std::cout << body << std::endl;
}

void callback(const Json::Value& val)
{
    std::cout << val["ret"] << std::endl;
}

int main()
{
    //0、先去掉内部日志。
    muduo::Logger::setLogLevel(muduo::Logger::FATAL);

    //1、创建接收消息requestor模块
    RPC::Client::Requestor::Ptr requestor = RPC::Client::RequestorFactory::create();
    RPC::MessageCallback onMessage = std::bind(&RPC::Client::Requestor::onResponse, requestor.get(),
    std::placeholders::_1, std::placeholders::_2);

    //2、创建客服端并将requestor中的回调函数设置进来,连接服务器，连接不上就一直阻塞
    RPC::BaseClient::Ptr client = RPC::ClientFactory::create("127.0.0.1", 9090);
    client->SetMessageCallback(onMessage);
    client->connect();

    //3、定义用户的业务入口
    RPC::Client::RpcCaller::Ptr caller = RPC::Client::CallerFactory::create(requestor);
    RPC::BaseConnection::Ptr conn = client->conn();
    //4、构建请求发送请求。
    std::cout << "----------test1----------" << std::endl;
    Json::Value val1;
    val1["nums1"] = 11;
    val1["nums2"] = 22;
    Json::Value ret;
    caller->call(conn, "Add", val1, ret);
    std::cout << "----------msg from server----------" <<std::endl;
    std::cout << ret["ret"] << std::endl;

    std::cout << "----------test2----------" << std::endl;
    Json::Value val2;
    val2["nums1"] = 11;
    val2["nums2"] = 33;
    std::future<Json::Value> future;
    caller->call(conn, "Add", val2, future);
    std::cout << "----------msg from server----------" <<std::endl;
    ret = future.get();
    std::cout << ret["ret"] << std::endl;

    std::cout << "----------test3----------" << std::endl;
    Json::Value val3;
    val3["nums1"] = 22;
    val3["nums2"] = 33;
    caller->call(conn, "Add", val3, callback);
    std::cout << "----------msg from server----------" <<std::endl;
    sleep(10);
    client->shutdown();
    return 0;
}